package com.woniu.service.elasticSearch;


import com.woniu.entity.TestOutside;
import com.woniu.entity.TestType;
import com.woniu.mapper.TestDetailMapper;
import com.woniu.mapper.TestOutsideMapper;
import com.woniu.mapper.TestTypeMapper;
import com.woniu.service.vo.ShowTestVo;

import org.elasticsearch.action.admin.indices.analyze.AnalyzeAction;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeRequestBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class
ElasticsearchForTest implements InitializingBean {

    @Autowired
    TestOutsideMapper testOutsideMapper;
    @Autowired
    TestDetailMapper testDetailMapper;
    @Autowired
    TestTypeMapper testTypeMapper;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    EsTestRepository esTestRepository;

    public void loadData(List<ShowTestVo> data) {
        esTestRepository.saveAll(data);
    }

    public void update(ShowTestVo showTestVo) {
        esTestRepository.save(showTestVo);
    }

    public void deleteOne(ShowTestVo showTestVo) {
        esTestRepository.delete(showTestVo);
    }

    public void deleteData() {
        esTestRepository.deleteAll();
    }

    public void deleteById(Long id) {
        esTestRepository.deleteById(id);
    }

    public void autoLoadAllData() {
        esTestRepository.saveAll(getAllTestVolist());
    }

    /**
     * 获取所有靶场列表
     *
     * @return 返回所有的靶场列表
     */
    public List<ShowTestVo> getAllTestVolist() {
        List<ShowTestVo> testVoList = new ArrayList<>();
        testVoList = testDetailMapper.selectList(null).stream().map(testDetail -> {
            TestOutside testOutside = testOutsideMapper.selectById(testDetail.getTestCode());
            TestType testType = testTypeMapper.selectById(testDetail.getTestTypeId());
            return new ShowTestVo(testOutside, testDetail, testType);
        }).collect(Collectors.toList());
        return testVoList;
    }

    /**
     * es根据map当中的多条件关键字分页查询，
     *
     * @param condition
     * @return
     */
    public Page<ShowTestVo> searchByCondition(Map<String, Object> condition) {
        Integer currentPage;
        Integer pageSize;

        if (condition.get("currentPage") == null) {
            currentPage = 1;
        } else {
            currentPage = Integer.parseInt(condition.get("currentPage").toString());
        }

        if (condition.get("pageSize") == null) {
            pageSize = 6;
        } else {
            pageSize = Integer.parseInt(condition.get("pageSize").toString());
        }

        Pageable pageable = PageRequest.of(currentPage - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (!StringUtils.isEmpty(condition.get("parentType"))) {
            String parentType = condition.get("parentType").toString();
            boolQueryBuilder.filter(QueryBuilders.termQuery("parentType", parentType));
        }
        if (!StringUtils.isEmpty(condition.get("searchByType"))) {
            String type = condition.get("searchByType").toString();
            boolQueryBuilder.filter(QueryBuilders.termQuery("testType", type));
        }
        if (!StringUtils.isEmpty(condition.get("difficulty")) && !"全部".equals(condition.get("difficulty"))) {
            String difficulty = condition.get("difficulty").toString();
            boolQueryBuilder.filter(QueryBuilders.termQuery("difficulty", difficulty));
        }
        if (!StringUtils.isEmpty(condition.get("keyword"))) {
            String keyword = condition.get("keyword").toString();
            boolQueryBuilder.filter(QueryBuilders.multiMatchQuery(keyword, "testName", "introduce", "simpleNote"));
        }

        String order = "heatRange";
        if (!StringUtils.isEmpty(condition.get("order"))) {
            order = condition.get("order").toString();
        }
//        nativeSearchQueryBuilder.withFields("testCode","testName","testType","testPictureUrl","visitors");
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(order).order(SortOrder.DESC));
        nativeSearchQueryBuilder.withPageable(pageable);
        return esTestRepository.search(nativeSearchQueryBuilder.build());

    }



    @Override
    public void afterPropertiesSet() throws Exception {

    }
}